/**
 * * tp标记变量要放到htm页面渲染
 */
// var listId = "{$parameter['list_id']}"
// var urlSelectInfoIndex = "__CONTROLLER__/SelectInfoIndex"
// var urlGetResultInfo = "__CONTROLLER__/getResultInfo"
// var urlSaveVoteData = "__CONTROLLER__/SaveVoteData"
// var urlGetIsUser = "__CONTROLLER__/getIsUser"

/**
 * * 复选框限制选择
 * @param {dom} name 复选框组名
 * @param {Number} num  限制可选择数
 * bug 只能选择取消，不能自动取消最后选择的选项
 * TODO 用队列判断，自动取消开始选择的选项
 */
function choiceLimit(name, num) {
  var choicearr = document.getElementsByName(name);
  var a = 0
  for (var i = 0; i < choicearr.length; i++) {
    if (choicearr[i].checked) {
      a += 1
    }
  }
  if (a > num) {

    // for (var i = 0; i < choicearr.length; i++) {
    //   if (!choicearr[i].checked) {
    //     choicearr[i].disabled = 'disabled'
    //   }
    // }
    $.toptip(`最多只能选${num}个`, 800)
    return false
  } else {
    return true
    for (var i = 0; i < choicearr.length; i++) {
      choicearr[i].removeAttribute('disabled')
    }
  }
}

$.ajax({
  type: "POST",
  url: urlGetResultInfo,
  data: {
    list_id: listId,
  },
  dataType: "json",
  success: function(response) {
    
    // 已投票
    if (response.errcode && response.errcode === 0) {
      
      console.dir(response)
      // 投票结果
      $.ajax({
        type: "POST",
        url: urlGetResultInfo,
        data: {
          "list_id": listId
        },
        dataType: "json",
        success: function(response) {

          let voteItem = '';
          console.log(response)

          if (response.data.title && response.data.title.length > -1) {

            for (let i = 0; i < response.data.title.length; i++) {
              let optionsTmp = '';
              voteItem += `<div class="topic-wrapper">
                      <div class="weui-cells__title" data-id="${response.data.title[i].id}" data-topic="${response.data.title[i].title}">
                        <span >${response.data.title[i].title}</span>
                        <span class="choice">[最多可选${response.data.title[i].choice || 1}项]</span>
                      </div>
                      <div class="weui-cells weui-cells_checkbox">`
              for (let j = 0; j < response.data.title[i].options.length; j++) {

                let tmpOptionItem = response.data.title[i].options[j]
                optionsTmp = `<label class="weui-cell weui-check__label" for="s${tmpOptionItem.id}">
                        <div class="weui-cell__hd">
                          <input type="checkbox" class="weui-check" name="vote${response.data.title[i].id}" data-select-num="${response.data.title[i].choice}" id="s${tmpOptionItem.id}" ${tmpOptionItem.selected === 1 ? "checked" : ''} data-selected="${tmpOptionItem.selected}" data-title_id="${tmpOptionItem.title_id}" data-name="${tmpOptionItem.options_content}">
                          <i class="weui-icon-checked"></i>
                        </div>
                        <div class="weui-cell__bd">
                          <p>${tmpOptionItem.options_content}</p>
                        </div>
                        <div class="weui-cell__ft poll-result">
                          <p class="poll-box"><span class="poll">${tmpOptionItem.num}</span>票</p>
                        </div>
                      </label>`
                voteItem += optionsTmp
              }
              voteItem += `</div></div>`
            }
            let htmlBtn = `<section class="btn-submit">
                    <a href="javascript:;" class="weui-btn weui-btn_primary" id="vote">修改投票</a>
                    <a href="javascript:;" class="weui-btn weui-btn_plain-primary" id="show-result">显示结果</a>
                  </section>`
            voteItem += htmlBtn
            $('.vote-box').append(voteItem)

            // $('#vote').addClass('weui-btn_disabled')
            // $('#vote').off('click')
            $('#vote').text('修改投票')

            $('.vote-box').on('click', '.topic-wrapper input', function() {
              $(this).each(function() {
                console.log($(this).attr('name'))
                let isChecked = choiceLimit($(this).attr('name'), $(this).data('select-num'))
                console.log($(this).data('select-num'))
                if (!isChecked) {
                  $(this).removeAttr('checked')
                }
              })
            })
          }
        }
      });
    } else {

      // 未投票
      let voteItem = '';
      if (response.data.title && response.data.title.length > -1) {

        for (let i = 0; i < response.data.title.length; i++) {
          let optionsTmp = '';
          voteItem += `<div class="topic-wrapper data-topic-box="${response.data.title[i].id}">
                  <div class="weui-cells__title" data-id="${response.data.title[i].id}" data-topic="${response.data.title[i].title}">
                    <span >${response.data.title[i].title}</span>
                    <span class="choice">[最多可选${response.data.title[i].choice || 1}项]</span>
                  </div>
                  <div class="weui-cells weui-cells_checkbox">`
          for (let j = 0; j < response.data.title[i].options.length; j++) {

            let tmpOptionItem = response.data.title[i].options[j]
            optionsTmp = `<label class="weui-cell weui-check__label" for="s${tmpOptionItem.id}">
                <div class="weui-cell__hd">
                  <input type="checkbox" class="weui-check" name="vote${response.data.title[i].id}" data-select-num="${response.data.title[i].choice}" id="s${tmpOptionItem.id}" ${tmpOptionItem.selected === 1 ? "checked" : ''} data-title_id="${tmpOptionItem.title_id}" data-name="${tmpOptionItem.options_content}" data-index="${j}">
                  <i class="weui-icon-checked"></i>
                </div>
                <div class="weui-cell__bd">
                  <p>${tmpOptionItem.options_content}</p>
                </div>
                <div class="weui-cell__ft poll-result">
                  <p class="poll-box"><span class="poll"></span>票</p>
                </div>
              </label>`
            voteItem += optionsTmp
          }
          voteItem += `</div></div>`
        }
        let htmlBtn = `<section class="btn-submit">
                <a href="javascript:;" class="weui-btn weui-btn_primary" id="vote">${response.data.checked == 1 ? '修改投票' : '投票'}</a>
                <a href="javascript:;" class="weui-btn weui-btn_plain-primary" id="show-result">显示结果</a>
              </section>`
        voteItem += htmlBtn
        $('.vote-box').append(voteItem);
      }

      let checkedArrIndex = []
      // dom限制复选框选择个数
      $('.vote-box').on('click', '.topic-wrapper input', function(evt) {
        $(this).each(function(index, item) {
          console.log($(item))
          let isChecked = choiceLimit($(this).attr('name'), $(this).data('select-num'))
          if (!isChecked) {
            $(this).removeAttr('checked')
          }
          // TODO 1.组装数据，用队列实现
          // checkedArrIndex.push({
          //   "vote": $(item).attr('name'),
          //   "selected": []
          // })
          // if($(item).is(':checked') && checkedArrIndex.length <= $(item).data('select-num')) {
          //   checkedArrIndex.push($(item).data('index'))
          // }
          // console.log('item', item)
          // console.log('index', index)
          // console.log($(this).is(':checked'))

          // 队列选择的方式
          // if ($(this).is(':checked')) {

          //   checkedArrIndex.push($(this).data('index'))
          // }

          // console.log(checkedArrIndex)
          // console.log($(this).data('select-num'))
          // // bug 点击选项闪屏
          // // choiceLimit($(this).attr('name'), $(this).data('select-num'))
          // if ($(this).is(':checked') && checkedArrIndex.length > $(this).data('select-num')) {

          //   let queue = checkedArrIndex.shift()
          //   let $name = $(item).attr('name')
          //   if ($(`input[name=${$name}]input[data-index=${queue}]`).is(':checked')) {
          //     $(evt.currentTarget.parent)
          //     $(`input[name=${$name}][data-index=${queue}]`).removeAttr('checked')
          //   } else {

          //     $(`input[name=${$name}][data-index=${queue}]`).prop('checked', 'checked')
          //   }
          // } else if (!$(this).is(':checked')) {

        //   checkedArrIndex.pop()
        //   Array.from(new Set(checkedArrIndex))
        // }
        });
      })

      // 显示投票结果事件
      $('.vote-box').on('click', '#show-result', function() {
        $.ajax({
          type: "POST",
          url: urlGetResultInfo,
          data: {
            "list_id": listId
          },
          dataType: "json",
          success: function(response) {
            console.log(response)
            let pollResult = []

            if (response.data.title && response.data.title.length > -1) {


              for (let i = 0; i < response.data.title.length; i++) {

                if (response.data.title[i] && response.data.title[i].options.length > -1) {

                  for (let j = 0; j < response.data.title[i].options.length; j++) {

                    pollResult.push(response.data.title[i].options[j].num)
                  }
                }
              }
            }
            console.log(pollResult)

            // 显示投票结果
            $.map($('.vote-box .topic-wrapper .poll-result').find('.poll'), function(item,
              itemIndex) {
              console.log(item)
              $(item).text(pollResult[itemIndex])
            })
          },
          error: function() {
            $.toast('请先投票')
          }
        });
      })
    }


    // TODO 原投票代码

    // 显示结果事件
    $('.vote-box').on('click', '#show-result', function(evt) {
      var $this = $(this)
      $(this).parent().prevAll().find('.poll-result').toggle(10, function() {})
      let textResult = $(this).text()
      $this.text(textResult === "显示结果" ? "隐藏结果" : "显示结果")
      $this.animate({

      })
    })

    $.ajax({
      type: "POST",
      url: urlGetIsUser,
      data: {
        "list_id": listId
      },
      dataType: "json",
      success: function(response) {
        console.log(response);
        console.log(response.data.is_poster)
        if (response.data.is_poster == 1) {
          $('#show-result').css('display', 'block')
        }
      }
    });
  },
  complete: function(response) {
    $('#vote').on('click', function() {
      let postData = [];
      //获取投票选项
      console.log($('.vote-box .topic-wrapper'))
      $.map($('.vote-box .topic-wrapper'), function(topic, topicIndex) {
        let tmp = []
        let itemData = []
    
        $.map($(topic).find('input'), function(item, itemIndex) {
    
          if ($(item).is(':checked')) {
            itemData.push({
              "id": $(item).attr('id').replace('s', ''),
              "name": $(item).data('name'),
              "value": itemIndex,
              "title_id": $(item).data('title_id')
            })
          }
        })
        postData.push({
          "list_id": listId,
          "data": itemData
        })
      })
      console.log(postData)
      $.ajax({
        type: "POST",
        url: urlSaveVoteData,
        data: {
          "data": postData
        },
        dataType: "json",
        success: function(response) {
          // TODO
          console.log(response);
          if (response.errcode === 0) {
            $.toast('投票成功', 1000)
            // $('#vote').addClass('weui-btn_disabled')
            // $('#vote').off('click')
            $('#vote').text('修改投票')
    
            // 投票结束取消复选框选择事件
            // $('.vote-box').off('click', 'input')
    
          // fixed 修复投票后页面选项还可以修改的问题
          // 允许再次修改
          // $('input[type=checkbox]').each(function () {
          //   console.log($(this))
          //   $(this).prop('disabled', 'disabled')
          // })
          }
        }
      });
    })
  }
});

$.ajax({
  type: "POST",
  url: urlList.getAppJssdkInfo,
  // url: 'https://herb.yicanfan123.com/mobile/api_get_signpackage.php',
  data: {
    url: window.location.href.split('/list_id')[0] || postData.locationUrl
  },
  dataType: "json",
  success: function(response) {
    console.log(response)
    if(response.data) {
      let jssdk = response.data
      console.log(jssdk)
      wx.config({
        debug: false,
        appId: jssdk.appId,
        timestamp: jssdk.timestamp,
        nonceStr: jssdk.nonceStr,
        signature: jssdk.signature,
        jsApiList: [
            // 所有要调用的 API 都要加到这个列表中
            'chooseImage', 
            'uploadImage', 
            'onMenuShareTimeline', 
            'hideOptionMenu', 
            'showMenuItems',
            'onMenuShareAppMessage'
        ]
      });
      wx.ready(function () {
        wx.onMenuShareAppMessage({
            title: "", // 分享标题
            desc: "", // 分享描述
            link: "", // 分享链接
            imgUrl: '', // 分享图标
            type: '', // 分享类型,music、video或link，不填默认为link
            dataUrl: '', // 如果type是music或video，则要提供数据链接，默认为空
            success: function success() {
                weui.toast('分享成功');
            },
            cancel: function cancel() {}
        });
        wx.onMenuShareTimeline({
            title: "", // 分享标题
            desc: "", // 分享描述
            link: "", // 分享链接
            imgUrl: '',
            success: function success() {
                weui.toast('分享成功');
            },
            cancel: function cancel() {}
        });
      });
    }
  }
})
